Cracking the safe [de Bruijn sequences, Lyndon word]

Time: O(K^N); Space: O(K^N); hard

There is a box protected by a password. The password is a sequence of n digits where each digit can be one of the first k digits 0, 1, …, k-1.

While entering a password, the last n digits entered will automatically be matched against the correct password.

For example, assuming the correct password is “345”, if you type “012345”, the box will open because the correct password matches the suffix of the entered password.

Return any password of minimum length that is guaranteed to open the box at some point of entering it.

Example 1:

Input: n = 1, k = 2

Output: “01” (“10” will be accepted too)

Example 2:

Input: n = 2, k = 2

Output: “00110” (“01100”, “10011”, “11001” will be accepted too)

Constraints:

  • n will be in the range [1, 4].

  • k will be in the range [1, 10].

  • k^n will be at most 4096.

Hints:

  1. We can think of this problem as the problem of finding an Euler path (a path visiting every edge exactly once) on the following graph: there are k^(n-1) nodes with each node having k edges. It turns out this graph always has an Eulerian circuit (path starting where it ends.) We should visit each node in “post-order” so as to not get stuck in the graph prematurely.

1.

[1]:
class Solution1(object):
    """
    Time: O(K^N)
    Space: O(K^N)
    """
    def crackSafe(self, n, k):
        """
        :type n: int
        :type k: int
        :rtype: str
        """
        M = k**(n-1)
        P = [q*k+i for i in range(k) for q in range(M)]    # rotate: i*k^(n-1) + q => q*k + i

        result = [str(k-1)]*(n-1)

        for i in range(k**n):
            j = i
            # concatenation in lexicographic order of Lyndon words
            while P[j] >= 0:
                result.append(str(j//M))
                P[j], j = -1, P[j]

        return ''.join(result)
[2]:
s = Solution1()

n = 1
k = 2
assert s.crackSafe(n, k) == "01" or "10"

n = 2
k = 2
assert s.crackSafe(n, k) == "00110" or "01100" or "10011" or "11001"

2.

[3]:
class Solution2(object):
    def crackSafe(self, n, k):
        """
        :type n: int
        :type k: int
        :rtype: str
        """
        result = [str(k-1)]*n
        lookup = {''.join(result)}
        total = k**n

        while len(lookup) < total:
            node = result[len(result)-n+1:]

            for i in range(k):
                neighbor = ''.join(node) + str(i)
                if neighbor not in lookup:
                    lookup.add(neighbor)
                    result.append(str(i))
                    break

        return ''.join(result)
[4]:
s = Solution2()

n = 1
k = 2
assert s.crackSafe(n, k) == "01" or "10"

n = 2
k = 2
assert s.crackSafe(n, k) == "00110" or "01100" or "10011" or "11001"

3. DFS

[5]:
class Solution3(object):
    def crackSafe(self, n, k):
        """
        :type n: int
        :type k: int
        :rtype: str
        """
        def dfs(k, node, lookup, result):
            for i in range(k):
                neighbor = node + str(i)
                if neighbor not in lookup:
                    lookup.add(neighbor)
                    result.append(str(i))
                    dfs(k, neighbor[1:], lookup, result)
                    break

        result = [str(k-1)]*(n-1)
        lookup = set()
        dfs(k, ''.join(result), lookup, result)

        return ''.join(result)
[6]:
s = Solution3()

n = 1
k = 2
assert s.crackSafe(n, k) == "01" or "10"

n = 2
k = 2
assert s.crackSafe(n, k) == "00110" or "01100" or "10011" or "11001"